<?php

class CompanyController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array( 
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('view','editInfo','repassword','recharge','preview','mask','portal','loginTemplates','comtemplates'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','admin','delete','create','update'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView()
	{  

        $id = "";
        if(Yii::app()->user->name =="admin" ){
            if(empty($_REQUEST['id'])){
               throw new CHttpException(404);  
           }else{
              $id=$_REQUEST['id'];
          } 
        } else{
            $id=Yii::app()->user->id;
        }
        $model=$this->loadModel($id); 
        $model->template =Company::model()->getTemplates($model->template);
		$this->render('view',array(
			 'model'=>$model,
		));
	}
   
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Company;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
 
		if(isset($_POST['Company']))
		{  
			$model->attributes=$_POST['Company'];

            if(!empty($model->password)){
			     $model->password = md5($model->password.Yii::app()->params['private_key']);
             }

			//保存上传图片 
		 	$uploadedimage = CUploadedFile::getInstance($model, 'logo');
		 	$datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->logo = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }

           	$model->point= $_POST['Company']['point'];

			      if($model->save()){
                //添加企业分类关系表
                foreach ($_POST['tags'] as $v) {
                    $companyTag = new CompanyTag();
                    $companyTag->companyid = $model->id;
                    $companyTag->tagid = $v;
                    $companyTag->save();
                } 
                //新闻公告分类
                $column = new Column();
                $column->name='新闻公告分类';
                $column->categorytype='0';
                $column->companyid= $model->id;
                $column->save();
                 //产品分类
                $column = new Column();
                $column->name='产品分类';
                $column->categorytype='1';
                $column->companyid= $model->id;
                $column->save();
                 //企业短信营销
                $smsmarket = new Smsmarket();
                $smsmarket->companyid=$model->id;
                $smsmarket->save();
				        $this->redirect(array('admin'));
            }
		} 
		$this->render('create',array(
			'model'=>$model,'templates'=>Company::model()->getTemplates(""),
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Company']))
		{
    			$oldpassword = $model->password; 
    			$oldlogoUrl = dirname(Yii::app()->basePath).$model->logo;
    			$oldpoint =  $model->point; 

    			$model->attributes=$_POST['Company'];

    			if($model->password != $oldpassword){ 
    				$model->password = md5($model->password.Yii::app()->params['private_key']); 
    			}

      			//判断是否更新短信条数
      			if($oldpoint != ($_POST['Company']['point']) ){
                $model->point= $_POST['Company']['point'];
             }

	        //更新上传文件
    	    $uploadedimage = CUploadedFile::getInstance($model, 'logo');
     	    $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->logo = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
                //判断是否旧的logo，如果存在并删除就文件
                if(file_exists($oldlogoUrl)){
                	unlink($oldlogoUrl);
                }
            } 

		     if($model->save()){
              // 更新企业分类关系表
                  $tags = CompanyTag::model()->find("companyid=:id", array(':id' => $model->id));
                  if (!empty($tags)) {
                      $tags->deleteAll("companyid=:id", array(':id' => $model->id));
                  }
                  if (!empty($_POST['tags'])) {
                      foreach ($_POST['tags'] as $v) {
                          $companyTag = new CompanyTag();
                          $companyTag->companyid = $model->id;
                          $companyTag->tagid = $v;
                          $companyTag->save();
                      }
                  }
              $this->redirect(array('admin'));
          }

    } 

		$this->render('update',array(
			'model'=>$model,'templates'=>Company::model()->getTemplates(""),
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		// $dataProvider=new CActiveDataProvider('Company');
		// $this->render('index',array(
		// 	'dataProvider'=>$dataProvider,
		// ));
		$this->redirect(array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Company('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Company']))
			$model->attributes=$_GET['Company'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}


    /**
     * 企业修改本身的基本信息
     *
     * @return void
     * @author 
     **/
    public function  actionEditInfo()
    {

        $model=$this->loadModel(Yii::app()->user->id);

        if(isset($_POST['Company']))
        { 
            $oldlogoUrl = dirname(Yii::app()->basePath).$model->logo; 
            $model->attributes=$_POST['Company']; 
            //更新上传文件
            $uploadedimage = CUploadedFile::getInstance($model, 'logo');
           
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $datetime=Yii::app()->format->formatDate(time());
                $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
                if (!file_exists($uploaddir)) {
                    mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
                }
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->logo = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
                //判断是否旧的logo，如果存在并删除就文件
                if(file_exists($oldlogoUrl)){
                    unlink($oldlogoUrl);
                }
            } 

            if($model->save()){ 
                unset($_POST['Company']);
                return $this->render('editInfo',array(
                   'model'=>$model,'message'=>'修改信息成功',
                   ));
            }

        } 

        $this->render('editInfo',array(
            'model'=>$model,
        ));
    }

    /**
     * 企业修改用户登陆模板
     *
     * @return void
     * @author 
     **/
    public function  actionLoginTemplates()
    {

        $model=$this->loadModel(Yii::app()->user->id);

        if(isset($_POST['Company']))
        {  
            $model->attributes=$_POST['Company'];  

            if($model->save()){ 
                unset($_POST['Company']);
                return $this->render('logintemplates',array(
                   'model'=>$model,'message'=>'修改用户登陆模板成功','templates'=>Company::model()->getTemplates(""),
                   ));
            }

        } 

        $this->render('logintemplates',array(
            'model'=>$model,'templates'=>Company::model()->getTemplates(""),
        ));
    }
    /**
     * undocumented function
     *
     * @return void
     * @author 
     **/
    public function actionRepassword()
    {
         $model=$this->loadModel(Yii::app()->user->id);
         $newarray=array("oldpassword"=>'','newpassword'=>'','respassword'=>'');

          if(isset($_POST['Company']))
        {  
              
             $newarray= $_POST['Company'];  

            if(empty($newarray['oldpassword'])){
                $model->addError('oldpassword','旧密码不能为空');
                 return $this->render('repassword',array(
                    'model'=>$model,'newarray'=>$newarray,
                )); 
            }
            if(empty($newarray['newpassword'])){
                $model->addError('newpassword','新密码不能为空');
                 return $this->render('repassword',array(
                    'model'=>$model,'newarray'=>$newarray,
                )); 
            }
             if(empty($newarray['respassword'])){
                $model->addError('respassword','确认密码不能为空');
                 return $this->render('repassword',array(
                    'model'=>$model,'newarray'=>$newarray,
                )); 
            }

             if($newarray['newpassword']!==$newarray['respassword']){
                $model->addError('respassword','确认密码与新密码不一致');
                 return $this->render('repassword',array(
                    'model'=>$model,'newarray'=>$newarray,
                )); 
            }
             if($newarray['oldpassword']===$newarray['newpassword']){
                $model->addError('newpassword','新密码与旧密码不能相同');
                 return $this->render('repassword',array(
                    'model'=>$model,'newarray'=>$newarray,
                )); 
            }

            if($model->password != md5($newarray['oldpassword'].Yii::app()->params['private_key'])){
                $model->addError('oldpassword','旧密码错误,请从新输入');
                 return $this->render('repassword',array(
                    'model'=>$model,'newarray'=>$newarray,
                )); 
            }

                
            $model->password = md5($newarray['newpassword'].Yii::app()->params['private_key']);

            if($model->save()){ 
                unset($_POST['Company']);
                return $this->render('repassword',array(
                   'model'=>$model,'newarray'=>array("oldpassword"=>'','newpassword'=>'','respassword'=>''),'message'=>'修改密码成功',
                   ));
            }

        } 

        $this->render('repassword',array(
            'model'=>$model,'newarray'=>$newarray,
        ));
    }


    /**
     * 短信充值
     * 
     **/
    public function actionRecharge()
    {
       $model=$this->loadModel(Yii::app()->user->id);  

       $this->render('recharge',array(
            'model'=>$model,'freearray'=>Company::model()->getSmsfree(),
        ));
    }

    /**
     * 设置企业成功页面
     *
     * @return void
     * @author 
     **/
    public function actionPortal()
    {
        $model=$this->loadModel(Yii::app()->user->id);  
        if(isset($_POST['Company']))
        {  
            $model->attributes=$_POST['Company'];  
            if($this->check_remote_file_exists($_POST['Company']['portalurl'])){ 
                if($model->save()){ 
                    unset($_POST['Company']);
                    return $this->render('portal',array(
                       'model'=>$model,'message'=>'修改登陆成功跳转页面成功',
                       ));
                }
            }else{
               return $this->render('portal',array(
                       'model'=>$model,'message'=>'输入的跳转页面无法访问,请重新输入',
                       )); 
            } 
        } 
         $this->render('portal',array(
            'model'=>$model,
        ));
    }


    /**
     * 判断传递进来的url是否能够访问 
     **/
    private function check_remote_file_exists($url) 
    { 
        $curl = curl_init($url); 
        // 不取回数据 
        curl_setopt($curl, CURLOPT_NOBODY, true); 
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); //不加这个会返回403，加了才返回正确的200，原因不明 
        // 发送请求 
        $result = curl_exec($curl); 
        $found = false; 
        // 如果请求没有发送失败 
        if ($result !== false)  { 
        // 再检查http响应码是否为200 
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
            if ($statusCode == 200){ 
                $found = true; 
            } 
        } 
        curl_close($curl); 
        return $found; 
    } 
    /**
     * 预览模板
     *
     * @return void
     * @author 
     **/
    
    public function actionPreview()
    {   
        if($_REQUEST['type']=='computer'){
            echo '<div id="previewdiv"> 
                <div id="previewleft">
                <div id="title">电脑(800*600)</div>
                <iframe scrolling="auto" src="'.Yii::app()->createUrl('api/login&gw_id=previewshowcompany&template='.$_REQUEST['template'].'&companyid='.$_REQUEST['companyid']).'" width="100%" height="100%" frameborder=1></iframe><div style="clear: both;"></div></div>
            </div>';  
        }else{
           echo '<div id="previewdiv">  
                <div id="previewright"> 
                <div id="previewback">
                <iframe scrolling="auto" src="'.Yii::app()->createUrl('api/login&gw_id=previewshowcompany&template='.$_REQUEST['template'].'&companyid='.$_REQUEST['companyid']).'" width="100%" height="100%" frameborder=1></iframe><div style="clear: both;"></div></div></div>
            </div>';    
        }
       
    }

    /**
     *  预览手机模板
     **/ 
    public function actionComtemplates()
    {     
        $model=$this->loadModel(Yii::app()->user->id);  
        echo '<div id="previewdiv"> 
                <div id="previewright"> 
                <div id="previewback">
                <iframe scrolling="auto" src="'.Yii::app()->createUrl('api/login&gw_id=previewshowcompany&template='.$model->template.'&companyid='.$model->id).'" width="100%" height="100%" frameborder=1></iframe><div style="clear: both;"></div></div></div>
            </div>';   
    }
    /**
     * undocumented function
     *
     * @return void
     * @author 
     **/
    public function actionMask()
    {
       echo '<div class="form allbox">  
                <div id="title" style="">是否已经支付成功!</div>
                <div id="title" class="titleleft"><button type="button" class="failure" onclick="javascript:failure();$.colorbox.close();">支付失败</button></div>
                <div id="title" class="titleleft"><button type="button" class="succeed" onclick="javascript:succeed();$.colorbox.close();">支付成功</button></div>
                <div style="clear: both;"></div>
            </div>';
    }

   
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Company the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Company::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Company $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='company-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
